package com.qianfeng.libra.cowshop.app.tasks;

import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Libra丶ZW on 2015/3/11 0011.
 */
public class SignupTask extends AsyncTask<String, Integer, JSONObject> {

    private TaskProcessor processor;
    public SignupTask(TaskProcessor processor) {
        this.processor = processor;
    }

    @Override
    protected JSONObject doInBackground(String... strings) {
        JSONObject ret = null;
        if (strings != null && strings[0].length() > 0) {
            String url = strings[0];
            HttpPost httpPost = new HttpPost(url);

            List<NameValuePair> param = new ArrayList<NameValuePair>();

            param.add(new BasicNameValuePair("uid",strings[1]));

            param.add(new BasicNameValuePair("from","2"));

            UrlEncodedFormEntity entitys = null;
            Log.d("MMMMMMMMMMMMMMMyPOSTUTILS", "2");
            try {
                entitys = new UrlEncodedFormEntity(param,"utf-8");
                httpPost.setEntity(entitys);
                Log.d("MMMMMMMMMMMMMMMyPOSTUTILS", "3");
                HttpClient httpClient = new DefaultHttpClient();
                HttpResponse response = httpClient.execute(httpPost);
                if(response.getStatusLine().getStatusCode() == 200){
                    Log.d("MMMMMMMMMMMMMMMyPOSTUTILS", "4");
                    HttpEntity entity = response.getEntity();

                    String result = EntityUtils.toString(entity);
                    Log.d("MMMMMMMMMMMMMMMyPOSTUTILS", result);
                    ret=new JSONObject(result);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return ret;
    }

    @Override
    protected void onPostExecute(JSONObject jsonObject) {
        Log.d("MMMMMMMMMMMMMMMyPOSTUTILS", "6");
        if (processor != null) {
            Log.d("MMMMMMMMMMMMMMMyPOSTUTILS", "7");
            processor.processResult(jsonObject);
        }

    }
}
